package com.bolt.common.ognl;

import com.bolt.common.utils.StrUtil;
import com.bolt.common.xml.GenericTokenParser;
import com.bolt.common.xml.TokenHandler;
import ognl.OgnlException;

/**
 * Created by Administrator on 2017/9/13.
 */
public class ExpressionUtil {


    public static String parseText(final String expr, final Object context) {
        TokenHandler parsedValueHandler = new TokenHandler() {
            @Override
            public String handleToken(String expression) {
                Object newValue = null;
                try {
                    newValue = OgnlCache.getValue(expression, context);
                } catch (OgnlException ex) {

                }
                return StrUtil.trimToEmpty(String.valueOf(newValue));
            }

        };

        GenericTokenParser parser = new GenericTokenParser("%{", "}", parsedValueHandler);
        String newValue = parser.parse(expr);
        return newValue;

    }


    public static boolean isExpression(String expr) {
        return expr != null && expr.startsWith("%{") && expr.endsWith("}");
    }

    public static boolean containsExpression(String expr) {
        return expr != null && expr.contains("%{") && expr.contains("}");
    }


    public static String stripExpression( String expr) {
        if (ExpressionUtil.isExpression(expr)) {
            return expr.substring(2, expr.length() - 1);
        }
        return expr;
    }


}
